package cn.itcast.zuoyebang.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceUtils {

    private SharedPreferences preference;
    private static PreferenceUtils instance = null; //唯一的实例
    private final String IS_LOGIN = "IS_LOGIN";  //变量的 Key
    private final String USER_NAME = "USER_NAME";

    private PreferenceUtils(Context ctx) {
        preference = ctx.getSharedPreferences("local",Context.MODE_PRIVATE);
    }

    public static PreferenceUtils getInstance(Context ctx) {
        if(instance != null) {
            return instance;
        }
        instance = new PreferenceUtils(ctx); //实例化只会执行一次
        return instance;
    }

    public boolean readLoginStatus() {
        return preference.getBoolean(IS_LOGIN,false);
    }

    public String readUserName() {
        return preference.getString(USER_NAME,"");
    }

    public void saveLoginStatus(boolean isLogin, String userName) {
        preference.edit().putBoolean(IS_LOGIN,  isLogin).apply();
        preference.edit().putString(USER_NAME,  userName).apply();
    }

    public void savePassword(String userName,String pwd) {
        //todo 加密pwd
        preference.edit().putString(userName, MD5Utils.getMD5(pwd)).apply();
       ;
    }

    public String getPassword(String userName) {
        return preference.getString(userName,"");
    }

    public Boolean isUserExist(String userName){
        String pwd = getPassword(userName);
        return pwd.length() > 0;
    }

}